package com.ulook.lookplanet.controller;

import com.ulook.lookplanet.bean.TUser;
import com.ulook.lookplanet.common.ExceptionCode;
import com.ulook.lookplanet.common.JsonResult;
import com.ulook.lookplanet.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述： 登陆
 *
 * @author L1998
 * @date 2021/3/26
 */
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登陆
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResult<TUser> login(HttpServletRequest request) {

        String id = request.getParameter("id");
        String password = request.getParameter("password");
        if(id == null || "".equals(id)){
            return new JsonResult<>(ExceptionCode.NULL_PARAM, "id为空");
        }

        TUser userParam = new TUser();
        try {
            int i = Integer.parseInt(id);
            userParam.setId(i);
        } catch (NumberFormatException e) {
            System.out.println("this is email");
        }
        userParam.setEmail(id);
        userParam.setPassword(password);
        System.out.println("login-user:  "+userParam);
        TUser user = loginService.login(userParam);
        return new JsonResult<>(user);
    }

    /**
     * 注册
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JsonResult<TUser> register(HttpServletRequest request){

        String name = request.getParameter("name");
        String id = request.getParameter("id");
        String password = request.getParameter("password");
        if(id == null || "".equals(id)){
            return new JsonResult<>(ExceptionCode.NULL_PARAM, "id为空");
        }

        TUser param = new TUser();
        param.setName(name);
        param.setEmail(id);
        param.setPassword(password);
        TUser res = loginService.register(param);
        if(res == null){
            return new JsonResult<>(ExceptionCode.EXIST_DATA, "该邮箱已被注册");
        }
        return new JsonResult<>(res);
    }
}
